package com.rong.shop.controller;

import com.rong.shop.controller.ex.*;
import com.rong.shop.pojo.User;
import com.rong.shop.service.IUserService;
import com.rong.shop.service.ex.InsertException;
import com.rong.shop.service.ex.UsernameDuplicatedException;
import com.rong.shop.utils.JsonResult;
import com.rong.shop.utils.RongUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.util.UUID;

@Controller
@RequestMapping("/users")
public class UserController extends BaseController{

    @Autowired
    private IUserService userService;

    /**
     * 第一种方式：进行try catch 以Json的形式返回。
     */
//    public JsonResult<Void> reg(User user){
//
//        JsonResult<Void> result = new JsonResult<Void>();
//
//        try {
//            userService.reg(user);
//            result.setState(200);
//            result.setMsg("用户添加成功");
//
//        } catch (UsernameDuplicatedException e) {
//            result.setState(400);
//            result.setMsg("用户名被占用！");
//
//        }catch (InsertException e) {
//            result.setState(400);
//            result.setMsg("添加用户失败");
//        }
//
//        return result;
//
//    }

    /**
     * 用户注册
     * @param user
     * @return
     */
    @RequestMapping("/reg")
    @ResponseBody
    public JsonResult<Void> reg(User user) {

        userService.reg(user);
        return new JsonResult<>(OK);

    }


    /**
     * 用户登录
     * @param username
     * @param password
     * @return
     */
    @RequestMapping("/login")
    @ResponseBody
    public JsonResult<User> login(String username, String password, HttpSession session){

        User u = userService.login(username, password);

        // 把数据装载session 里面
        session.setAttribute("uid",u.getUid());
        session.setAttribute("username",u.getUsername());
        session.setAttribute("avatar", u.getAvatar());

        // 输出session的uid username
//        RongUtils.print("login C层=》");
//        System.out.println(getUsernameFromSession(session));
//        System.out.println(getUidFromSession(session));
//        System.out.println(u.getAvatar());

        return new JsonResult<User>(OK, u);
    }

    @RequestMapping("/getInfoByUid")
    @ResponseBody
    public JsonResult<User> getInfoByUid(HttpSession session){
        User u = userService.getUserByUid(getUidFromSession(session));
        return new JsonResult<>(OK, u);
    }


    @RequestMapping("/changePwd")
    @ResponseBody
    public JsonResult<User> changePwd(String oldPwd, String newPwd, HttpSession session){
        userService.changePwd(getUidFromSession(session), getUsernameFromSession(session), oldPwd, newPwd);
        return new JsonResult<User>(OK);
    }

    @RequestMapping("/changeAvatar")
    @ResponseBody
    public JsonResult<String> changeAvatar(HttpSession session, @RequestParam("file") MultipartFile file){

        if (file.isEmpty()) {
            throw new FileEmptyException("文件为空");
        }
        if(file.getSize() > AVATAR_MAX_SIZE){
            throw new FileSizeException("文件过大");
        }
        if(!AVATAR_TYPE.contains(file.getContentType())){
            throw new FileTypeException("文件类型不匹配");
        }

        // 上传文件的绝对路径： .../updaload/
//        String parent = session.getServletContext().getRealPath("upload");
//RongUtils.print(parent.toString());
//        File dir = new File(parent);
//        if(!dir.exists()){
//            dir.mkdirs();
//            RongUtils.print("mkdirs");
//        }

        // 获取文件名： 为的是拿到后缀 .png
        String originalFilename = file.getOriginalFilename();
        int index = originalFilename.lastIndexOf(".");
        String suffix = originalFilename.substring(index);

        // 拼接成随机的文件名.png
        String UUIDName = UUID.randomUUID().toString().toUpperCase();
        String avatarName = UUIDName + suffix;

        // 进行文件的写入
        String dir = "C:\\Users\\Administrator\\Desktop\\CodeDemo\\shopping\\demo\\src\\main\\resources\\static\\upload\\avatar";
        File dest = new File(dir, avatarName); // 是一个空文件
        try {
            file.transferTo(dest);             // 将二进制文件输出到文件中
        } catch (FileStateException e) {
            throw new FileStateException("文件状态异常");
        }catch (IOException e) {
            throw new FileUploadIOException("文件读写异常");
        }

        // 上传成功后开始更新 avatar字段数据
        Integer uid = getUidFromSession(session);
        String username = getUsernameFromSession(session);
        String avatar = "/upload/avatar/" + avatarName;

        userService.changeAvatar(uid, username, avatar);

        return new JsonResult<String>(OK, avatar);
    }

    @RequestMapping("/changeInfo")
    @ResponseBody
    public JsonResult<User> changeInfo(HttpSession session, User user){
        userService.changeInfo(getUidFromSession(session),
                getUsernameFromSession(session),user);
        return new JsonResult<>(OK);
    }


}
